#!/usr/local/util/bin/python                                                                                                 
#
## @package edi_common
# Common data and functions for Easydoneit CLI.
# python style<br>
# basic functions that can be reused outside easydoneit<br>
#
# Copyright (C) 2014 Spartatek AB
#
# contact@spartatek.se
# http://spartatek.se
#
# EASYDONEIT CLI is free software: you can redistribute it and/or modify
# it under the terms of the GNU Genereric Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# EASYDONIT CLI is distributed in the hope that it will be usesul,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Genereral Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see
# GNU licences http://www.gnu.org/licenses

import os
import logging

#==========================================================================
# Setup logger
#==========================================================================
if __name__ == '__main__':
  console = logging.StreamHandler() #pragma: no cover
  formatter = logging.Formatter('%(levelname)-8s (%(name)s) %(message)s') #pragma: no cover
  console.setFormatter(formatter) #pragma: no cover
  console.setLevel(logging.INFO) #pragma: no cover
  logging.getLogger('').addHandler(console) #pragma: no cover
logger = logging.getLogger(os.path.basename(__file__))
logger.setLevel(logging.INFO);
#==========================================================================
# Logger has been set up
#==========================================================================



#==========================================================================

## Find all files in tree path.
# @return list of paths for files
# @param[in] path to tree
# @ingroup EDI_CORE
def ffind(path, namefs=None, relative=True):
    """
    Finds files in the directory tree starting at 'path' (filtered by the
    functions in the optional 'namefs' sequence); if the 'relative'
    flag is not set, the result sequence will contain absolute paths.                                                        

    Returns a sequence of paths for files found.
    """
    if not os.access(path, os.R_OK):
        logger.error("cannot access path: '%s'" % path) #pragma: no cover

    fileList = []
    try:
        for dir, subdirs, files in os.walk(path):
            fileList.extend(['%s%s%s' % (dir, os.sep, f) for f in files])
        if not relative: fileList = map(os.path.abspath, fileList)
        if namefs: 
            for ff in namefs: fileList = filter(ff, fileList) #pragma: no cover
    except Exception, e: logger.error(str(e)) #pragma: no cover
    return(fileList)
